namespace HZY.Core.Excel;

/// <summary>
/// excel 工具类
/// </summary>
public static class ExcelUtil
{
    #region Excel 映射

    /// <summary>
    /// 获取字典集合
    /// </summary>
    /// <returns></returns>
    public static byte[] GetExcelByDict<TEntity>(List<TEntity> data)
        where TEntity : class, new()
    {
        if (data.Count == 0)
        {
            return [];
        }

        var dynamicExcelColumnList = new List<DynamicExcelColumn>();

        var excelData = new List<Dictionary<string, object?>>();

        var index = 0;

        // 将 data 组装为 excelData
        foreach (var item in data)
        {
            index++;
            var type = item.GetType();
            var dict = new Dictionary<string, object?>();
            foreach (var property in type.GetProperties())
            {
                // 只有打了 excel 标记的字段才能导出
                var excelAttribute = property.GetCustomAttribute<ExcelColumnAttribute>();
                if (excelAttribute is null)
                {
                    continue;
                }

                var key = excelAttribute.Name;

                // 特殊处理一下如果 同时存在 Dict 和 Excel 标记，那么数据的值只能去读取 ToField 的值
                var dictAttribute = property.GetCustomAttribute<DictAttribute>();
                if (dictAttribute is not null)
                {
                    var keyName = dictAttribute.ToField;
                    if (string.IsNullOrWhiteSpace(keyName))
                    {
                        throw new Exception("请设置 ToField 字段");
                    }
                    else
                    {
                        var value = type.GetProperty(keyName)?.GetValue(item);
                        dict[key] = value;
                    }
                }
                else
                {
                    var value = property.GetValue(item);
                    dict[key] = value;
                }

                if (index == 1)
                {
                    // 添加动态咧 配置
                    dynamicExcelColumnList.Add(new DynamicExcelColumn(key)
                    {
                        Name = excelAttribute.Name,
                        // Index = excelAttribute.Index,
                        Width = excelAttribute.Width,
                        Format = excelAttribute.Format
                    });
                }
            }

            excelData.Add(dict);
        }

        // excel 配置
        var config = new OpenXmlConfiguration
        {
            DynamicColumns = dynamicExcelColumnList.ToArray()
        };

        using var stream = new MemoryStream();
        stream.SaveAs(excelData, configuration: config);

        // 将 stream 转为 byte[]
        return stream.ToArray();
    }

    #endregion
}